// 判断是否为数值
function isNumber (val) {
  const regPos = /^\d+(\.\d+)?$/; // 非负浮点数
  const regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; // 负浮点数
  if (regPos.test(val) || regNeg.test(val)) {
    return true;
  } else {
    return false;
  }
}
// 将科学计数法转为数值类型
function toNonExponential (num) {
  const m = Number(num).toExponential().match(/\d(?:\.(\d*))?e([+-]\d+)/);
  return Number(num).toFixed(Math.max(0, (m[1] || '').length - m[2]));
}

// 剔除html标签，只保留内容
function nohtml (html) {
  const str = html || '';
  return str.replace(/<\/?.+?>/g, '');
}

// 简化小数位数
// @param {string, number} num 数字
// @param {number} maxDigit 最长的小数位数
function simplifyNumber (num, maxDigit = 2) {
  const numArr = String(num).split('.');
  if (numArr.length < 2) {
    return Number(numArr);
  } else {
    if (numArr[1].length > maxDigit) {
      return Number(Number(num).toFixed(maxDigit));
    } else {
      return Number(num);
    }
  }
}

/* export default {
  // 判断是否为数值
  isNumber: function (val) {
    const regPos = /^\d+(\.\d+)?$/; // 非负浮点数
    const regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; // 负浮点数
    if (regPos.test(val) || regNeg.test(val)) {
      return true;
    } else {
      return false;
    }
  },
  // 将科学计数法转为数值类型
  toNonExponential: function (num) {
    const m = num.toExponential().match(/\d(?:\.(\d*))?e([+-]\d+)/);
    return num.toFixed(Math.max(0, (m[1] || '').length - m[2]));
  }
}; */

/**
 * 小数转分数
 * @param {number} decimals 小数
 * @param {number} accuracy 精度，即小数位数
 */
function decimalsToFractional (decimals, accuracy) {
  let acc = accuracy;
  if (!accuracy) {
    const str = String(Number(decimals)).split('.');
    acc = str.length > 1 ? str[1].length : 2;
  }
  if (acc > 6) acc = 6;

  const formatDecimals = Number(decimals).toFixed(acc); // (~~(decimals * Math.pow(10, acc))) / Math.pow(10, acc);
  let denominator = Math.pow(10, acc); // 初始化分母
  let numerator = formatDecimals * denominator // 初始化分子
  let bigger = 0
  function recursion () {
    bigger = denominator > numerator ? denominator : numerator
    for (let i = bigger; i > 1; i--) {
      if (
        Number.isInteger(numerator / i) &&
              Number.isInteger(denominator / i)) {
        numerator = numerator / i
        denominator = denominator / i
        recursion()
      }
    }
  }
  recursion()
  return `${numerator}/${denominator}`
}

/**
 * 十进制转26进制，即转成excel的列号
 * @param {Number} num 10进制数据
 * @returns {String} 列号
 */
function convertDSTo26BS (num) {
  let code = '';
  const reg = /^\d+$/g;
  if (!reg.test(num)) {
    return code;
  }
  while (num > 0) {
    let m = num % 26
    if (m == 0) {
      m = 26;
    }
    code = String.fromCharCode(64 + parseInt(m)) + code;
    num = (num - m) / 26;
  }
  return code;
};

/**
 * 26进制转十进制，即把excel的列号转成数字
 * @param {String} code 列号
 * @returns 数字
 */
function convert26BSToDS (code) {
  let num = -1;
  const reg = /^[A-Z]+$/g;
  if (!reg.test(code)) {
    return num;
  }
  num = 0;
  for (let i = code.length - 1, j = 1; i >= 0; i--, j *= 26) {
    num += (code[i].charCodeAt() - 64) * j;
  }
  return num;
};

/**
 * 字符串转换为十六进制
 * @param {string} str 字符串
 * @returns {string} 十六进制字符串
 */
function stringToHex (str, split = ',') {
  let val = '';

  for (let i = 0; i < str.length; i++) {
    if (val == '') { val = str.charCodeAt(i).toString(16); } else { val += split + str.charCodeAt(i).toString(16); }
  }

  return val;
}

/**
 * 十六进制转换为字符串
 * @param {string} str 十六进制字符串
 * @returns {string} 字符串
 */
function hexToString (str) {
  let val = '';
  const arr = str.split(',');

  for (let i = 0; i < arr.length; i++) {
    val += arr[i].fromCharCode(i);
  }

  return val;
}

/**
 * 处理文件类型
 * @param {string} fileType 文件后缀名
 * @returns {string} 文档类型
 */
function handleDocType (fileType) {
  let docType = '';
  // word类型
  const fileTypesDoc = [
    '.doc',
    '.docm',
    '.docx',
    '.docxf',
    '.dot',
    '.dotm',
    '.dotx',
    '.epub',
    '.fodt',
    '.fb2',
    '.htm',
    '.html',
    '.mht',
    '.odt',
    '.oform',
    '.ott',
    '.oxps',
    '.pdf',
    '.rtf',
    '.txt',
    '.djvu',
    '.xml',
    '.xps'
  ];
  // excel类型
  const fileTypesCsv = [
    '.csv',
    '.fods',
    '.ods',
    '.ots',
    '.xls',
    '.xlsm',
    '.xlsx',
    '.xlt',
    '.xltm',
    '.xltx'
  ];
  // powerpoint类型
  const fileTypesPPt = [
    '.fodp',
    '.odp',
    '.otp',
    '.pot',
    '.potm',
    '.potx',
    '.pps',
    '.ppsm',
    '.ppsx',
    '.ppt',
    '.pptm',
    '.pptx'
  ];

  if (fileTypesDoc.includes(fileType)) {
    docType = 'word'; // 文本文档
  }

  if (fileTypesCsv.includes(fileType)) {
    docType = 'cell'; // 电子表格
  }

  if (fileTypesPPt.includes(fileType)) {
    docType = 'slide'; //  演示文稿
  }
  return docType;
}

// 验证IP地址
function isValidIP (ip) {
  const reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
  let matchIp = ip;
  if (matchIp.indexOf(':') > -1) {
    matchIp = matchIp.split(':')[0];
  }
  return reg.test(matchIp);
}

// 判断是否包含汉字
function existChineseCharacter (str) {
  if (/[\u4E00-\u9FA5\uFE30-\uFFA0]/.test(str)) {
    return true;
  } else {
    return false;
  }
}

/**
 * 读取字符串的长度，汉字长度为2
 * @param {*} str
 * @returns
 */
export const getByteLen = (str) => {
  let len = 0;
  for (let i = 0; i < str.length; i++) {
    str.charCodeAt(i) < 256 ? (len += 1) : (len += 2)
  }
  return len;
}

export {
  isNumber,
  toNonExponential,
  nohtml,
  simplifyNumber,
  decimalsToFractional,
  convertDSTo26BS,
  convert26BSToDS,
  stringToHex,
  hexToString,
  handleDocType,
  isValidIP,
  existChineseCharacter
};
